package com.itjiange.springbootinit.controller;

import cn.hutool.json.JSONUtil;
import org.springframework.context.annotation.Profile;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * @author ItJiange
 * @date 2023/12/16
 */
@RestController
@RequestMapping("/thread")
@Profile({"dev", "test"})
public class ThreadController {

    @Resource
    private ThreadPoolExecutor threadPoolExecutor;

    @GetMapping("/add")
    public void add(String name){
        CompletableFuture.runAsync(() -> {
            System.out.println("待执行任务：" + name + ", 当前线程："+ Thread.currentThread().getName());
            try {
                Thread.sleep(600000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }, threadPoolExecutor);
    }

    @GetMapping("/get")
    public String get() {
        Map<String, Object> map = new HashMap<>();
        map.put("核心线程数：", threadPoolExecutor.getCorePoolSize());
        map.put("最大线程数：", threadPoolExecutor.getMaximumPoolSize());
        map.put("活跃线程数：", threadPoolExecutor.getActiveCount());
        map.put("线程池中线程数：", threadPoolExecutor.getPoolSize());
        map.put("线程池中等待队列：", threadPoolExecutor.getQueue().size());
        map.put("线程池中完成任务数：", threadPoolExecutor.getCompletedTaskCount());
        return JSONUtil.toJsonStr(map);
    }
}
